#include "agent.h"
#include "pushgateway_client.h"
#include "scaler.h"
#include "utils.h"
#include "common.h"

#include <netdb.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string>
#include <malloc.h>

void push_db_data(std::string addr, std::string query, std::string error, long execute_micro_time)
{
    PushGatewayClient *pushgateway_client = PushGatewayClient::newInstance();
    Scaler *sc_total = new Scaler;
    Scaler *sc_second = new Scaler;

    if (error == "")
    {
        sc_total->setIndex(INDEX_SQL_USEGE_TOTAL);
        sc_total->addItem(ITEM_SQL_ADDR, addr);
        sc_total->addItem(ITEM_SQL_NAME, query);
        pushgateway_client->setCounter(sc_total);
    }
    else
    {
        sc_total->setIndex(INDEX_SQL_USEGE_ERROR_TOTAL);
        sc_total->addItem(ITEM_SQL_ADDR, addr);
        sc_total->addItem(ITEM_SQL_NAME, query);
        sc_total->addItem(ITEM_SQL_ERROR, error);
        pushgateway_client->setCounter(sc_total);
    }

    sc_second->setIndex(INDEX_SQL_USEGE_DURATION_S);
    sc_second->addItem(ITEM_SQL_ADDR, addr);
    sc_second->addItem(ITEM_SQL_NAME, query);
    pushgateway_client->setBucket(sc_second, execute_micro_time * pow(0.1, MONITORPRO_HISTOGRAM_DECIAML));

    delete sc_total;
    delete sc_second;
    sc_total = nullptr;
    sc_second = nullptr;
    malloc_trim(0);
}

void push_redis_data(std::string addr, std::string query, std::string error, long execute_micro_time)
{
    PushGatewayClient *pushgateway_client = PushGatewayClient::newInstance();
    Scaler *sc_total = new Scaler;
    Scaler *sc_second = new Scaler;

    if (error == "")
    {
        sc_total->setIndex(INDEX_REDIS_USEGE_TOTAL);
        sc_total->addItem(ITEM_REDIS_ADDR, addr);
        sc_total->addItem(ITEM_REDIS_NAME, query);
        pushgateway_client->setCounter(sc_total);
    }
    else
    {
        sc_total->setIndex(INDEX_REDIS_USEGE_ERROR_TOTAL);
        sc_total->addItem(ITEM_REDIS_ADDR, addr);
        sc_total->addItem(ITEM_REDIS_NAME, query);
        sc_total->addItem(ITEM_REDIS_ERROR, error);
        pushgateway_client->setCounter(sc_total);
    }

    sc_second->setIndex(INDEX_REDIS_USEGE_DURATION_S);
    sc_second->addItem(ITEM_REDIS_ADDR, addr);
    sc_second->addItem(ITEM_REDIS_NAME, query);
    pushgateway_client->setBucket(sc_second, execute_micro_time * pow(0.1, MONITORPRO_HISTOGRAM_DECIAML));

    // sc_total->clean();
    // sc_second->clean();
    delete sc_total;
    delete sc_second;
    sc_total = nullptr;
    sc_second = nullptr;
    malloc_trim(0);
}